<!-- 现在的这个表格导出已经支持表格样式的导出 -->
<template>
    <div class="test">
        <a-button  type="primary" @click="exportTableHandler">表格导出按钮</a-button>
        <br>
        <a-switch size="small" v-model:checked="hiddenSame" @change="hiddenSameChangeHandler" />
        <span>{{ hiddenSame ? '关闭隐藏' : '隐藏相同项' }}</span>
        <a-table :columns="finalColumns" :key="renderIndex" :data-source="finalData" size="middle" :pagination="false"
            :scroll="{ x: 'calc(700px + 50%)', y: 500 }">
            <!-- <a-table :columns="finalColumns" :key="index" :data-source="finalData" size="middle" :pagination="false"> -->
            <template #headerCell="{ column, record }">
                <template v-if="column.dataIndex !== 'name' && !column.children">
                    <a-tag color="#E6F8F2" style="color: #00BE7A;width: 60%;">{{ column.title }}</a-tag>
                </template>
            </template> </a-table>
    </div>
</template>
  
<script setup lang='ts'>
import { color } from 'echarts';
import { cloneDeep, includes } from 'lodash';
import { onMounted, reactive, ref, watch } from 'vue';
// import { any, array, string } from 'vue-types';
// import { utils, writeFile, write } from 'xlsx';
// import{ utils, writeFile } from '../../public/xlsx.full.min.js'
// import * as XLSX from 'xlsx-style-vite';
import { utils, write } from 'xlsx-style-vite';

// 定义是否隐藏相同项的开关
let hiddenSame = ref<boolean>(false)

let bcsCompareList = [
    {
        "Id": 91,
        "BcsName": "bcstest123",
        "EceId": 4,
        "ProjectId": 73,
        "PcId": 0,
        "Sid": 0,
        "Content": "{\"year_total\":[2022,2023],\"income\":{\"car_output_rfq\":[100001,10000,110001],\"ir_rate_rfq\":[95,96,-1],\"ir_number_rfq\":[9501,9500,19001],\"car_output\":[8500,8500,17000],\"ir_rate\":[95,95,-1],\"ir_number\":[8075,8075,16150],\"hardware_price\":[{\"Price\":1,\"Percent\":100},{\"Price\":0,\"Percent\":100},{\"Price\":-1,\"Percent\":-1}],\"software_price\":[{\"Price\":0,\"Percent\":100},{\"Price\":0,\"Percent\":100},{\"Price\":-1,\"Percent\":-1}],\"develop_one\":[0,0,0],\"software_service\":[0,0,0],\"hardware_income\":[8075,0,8075],\"software_income\":[0,0,0]},\"three_cost\":{\"hardware_buy_price\":[{\"Price\":10,\"Percent\":100},{\"Price\":0,\"Percent\":100},{\"Price\":-1,\"Percent\":-1}],\"all_buy_cost\":[807500,0,807500],\"supply_developer_money\":[0,0,0],\"three_all_cost\":[80750,0,807500]},\"in_platform\":{\"ark_sw\":[0,0,0],\"ark_develop\":[0,0,0],\"software_tools\":[{\"Price\":0,\"IrNumber\":8075},{\"Price\":0,\"IrNumber\":8075},{\"Price\":0,\"IrNumber\":1}],\"ark_hardware_develop\":[0,0,0],\"drive_platform_price\":[156,156,312],\"stop_platform_price\":[54,54,108],\"base_drive_price\":[7.1,7.1,14.2],\"other_func\":[0,0,0],\"software_platform_dev\":[1753082.5,1753082.5,3506165]},\"cus_cost\":{\"develop_people_cost\":[0,0,0],\"develop_no_people_cost\":[0,0,0],\"cus_project_dev_cost\":[0,0,0]},\"over_head\":{\"period_fee\":[0,0,0]},\"over_view\":{\"all_sales_income\":[0,0,0],\"all_develop_fee\":[1753082.5,1753082.5,3506165],\"all_cost\":[0,0,0],\"tax_profit\":[0,0,0],\"tax_profit_percent\":[0,0,-1]}}",
        "PcName": "",
        "BcsType": "",
        "CarOutput": 17000,
        "Round": 0,
        "Operator": "zhaoshubao",
        "CreatedAt": 1681972574
    },
    {
        "Id": 89,
        "BcsName": "bcstest123",
        "EceId": 4,
        "ProjectId": 73,
        "PcId": 0,
        "Sid": 0,
        "Content": "{\"year_total\":[2022,2023],\"income\":{\"car_output_rfq\":[10000,10000,20000],\"ir_rate_rfq\":[95,95,-1],\"ir_number_rfq\":[9500,9500,19000],\"car_output\":[8500,8500,17000],\"ir_rate\":[95,95,-1],\"ir_number\":[8075,8075,16150],\"hardware_price\":[{\"Price\":0,\"Percent\":100},{\"Price\":0,\"Percent\":100},{\"Price\":-1,\"Percent\":-1}],\"software_price\":[{\"Price\":0,\"Percent\":100},{\"Price\":0,\"Percent\":100},{\"Price\":-1,\"Percent\":-1}],\"develop_one\":[0,0,0],\"software_service\":[0,0,0],\"hardware_income\":[0,0,0],\"software_income\":[0,0,0]},\"three_cost\":{\"hardware_buy_price\":[{\"Price\":0,\"Percent\":100},{\"Price\":0,\"Percent\":100},{\"Price\":-1,\"Percent\":-1}],\"all_buy_cost\":[0,0,0],\"supply_developer_money\":[0,0,0],\"three_all_cost\":[0,0,0]},\"in_platform\":{\"ark_sw\":[0,0,0],\"ark_develop\":[0,0,0],\"software_tools\":[{\"Price\":0,\"IrNumber\":8075},{\"Price\":0,\"IrNumber\":8075},{\"Price\":0,\"IrNumber\":0}],\"ark_hardware_develop\":[0,0,0],\"drive_platform_price\":[156,156,312],\"stop_platform_price\":[54,54,108],\"base_drive_price\":[7.1,7.1,14.2],\"other_func\":[0,0,0],\"software_platform_dev\":[1753082.5,1753082.5,3506165]},\"cus_cost\":{\"develop_people_cost\":[0,0,0],\"develop_no_people_cost\":[0,0,0],\"cus_project_dev_cost\":[0,0,0]},\"over_head\":{\"period_fee\":[0,0,0]},\"over_view\":{\"all_sales_income\":[0,0,0],\"all_develop_fee\":[1753082.5,1753082.5,3506165],\"all_cost\":[0,0,0],\"tax_profit\":[0,0,0],\"tax_profit_percent\":[0,0,-1]}}",
        "PcName": "",
        "BcsType": "",
        "CarOutput": 17000,
        "Round": 0,
        "Operator": "zhaoshubao",
        "CreatedAt": 1681972000
    }
]
let test = JSON.parse('{\"year_total\":[2022,2023],\"income\":{\"car_output_rfq\":[100001,10000,110001],\"ir_rate_rfq\":[95,96,-1],\"ir_number_rfq\":[9501,9500,19001],\"car_output\":[8500,8500,17000],\"ir_rate\":[95,95,-1],\"ir_number\":[8075,8075,16150],\"hardware_price\":[{\"Price\":1,\"Percent\":100},{\"Price\":0,\"Percent\":100},{\"Price\":-1,\"Percent\":-1}],\"software_price\":[{\"Price\":0,\"Percent\":100},{\"Price\":0,\"Percent\":100},{\"Price\":-1,\"Percent\":-1}],\"develop_one\":[0,0,0],\"software_service\":[0,0,0],\"hardware_income\":[8075,0,8075],\"software_income\":[0,0,0]},\"three_cost\":{\"hardware_buy_price\":[{\"Price\":10,\"Percent\":100},{\"Price\":0,\"Percent\":100},{\"Price\":-1,\"Percent\":-1}],\"all_buy_cost\":[807500,0,807500],\"supply_developer_money\":[0,0,0],\"three_all_cost\":[80750,0,807500]},\"in_paoa_to_sheetlatform\":{\"ark_sw\":[0,0,0],\"ark_develop\":[0,0,0],\"software_tools\":[{\"Price\":0,\"IrNumber\":8075},{\"Price\":0,\"IrNumber\":8075},{\"Price\":0,\"IrNumber\":1}],\"ark_hardware_develop\":[0,0,0],\"drive_platform_price\":[156,156,312],\"stop_platform_price\":[54,54,108],\"base_drive_price\":[7.1,7.1,14.2],\"other_func\":[0,0,0],\"software_platform_dev\":[1753082.5,1753082.5,3506165]},\"cus_cost\":{\"develop_people_cost\":[0,0,0],\"develop_no_people_cost\":[0,0,0],\"cus_project_dev_cost\":[0,0,0]},\"over_head\":{\"period_fee\":[0,0,0]},\"over_view\":{\"all_sales_income\":[0,0,0],\"all_develop_fee\":[1753082.5,1753082.5,3506165],\"all_cost\":[0,0,0],\"tax_profit\":[0,0,0],\"tax_profit_percent\":[0,0,-1]}}')

let renderIndex = ref(0)
// 定义变量接收最终的表头信息
let finalColumns = reactive<Array<any>>([])
// 定义变量存储最终的表格内部数据
let finalData = reactive<Array<any>>([])

// 定义数据处理的函数
const dealBcsCompareListDataFun = (compareList: Array<any>, isHiddenSame: boolean) => {

    let yearColumns: Array<any> = []
    let tableContent: Array<any> = []

    compareList.forEach((item, index) => {
        // 得到每一项的年份数据
        // console.log('测试当前项',item);
        let { tableHeader, tableBody } = dealContentDataFun(JSON.parse(item.Content), item.Id)
        yearColumns.push(tableHeader)
        // 得到每一项的表格数据
        if (index == 0 && tableContent.length <= 0) {
            tableContent = cloneDeep(tableBody)
        } else {
            tableContent.forEach(itemRow => {
                let sameObj = tableBody.filter(itm => itm.basicName == itemRow.basicName)[0]
                Object.assign(itemRow, sameObj)
            })
        }
    })
    yearColumns.unshift({
        title: 'BCS版本',
        dataIndex: 'name',
        key: 'name'
    })
    console.log('完整表头数据', yearColumns);
    console.log('完整表体', tableContent);

    // 当打开隐藏相同项的开关时需要对数据进行再一次处理，

    let yearArr: Array<string> = []
    if (isHiddenSame) {
        // 首先拿到所有的年份信息
        yearColumns.forEach((item) => {
            if (item.children && item.children.length > 0) {
                item.children.forEach((itm: any) => {
                    if (!yearArr.includes(itm.title.toString())) {
                        yearArr.push(itm.title.toString())
                    }
                })
            }
        })

        let hiddenContent = cloneDeep(tableContent)

        let arr: Array<any> = []
        // 处理内容信息
        hiddenContent.forEach((item, index) => {
            delete item.name
            delete item.basicName
            // console.log('每一项', item);

            let sign = Object.values(item)[0]
            let allRepeat = Object.values(item).every(itm => {
                return itm == sign
            })

            // console.log('是否重复');
            if (allRepeat) {
                arr.push(index)
            } else {
                yearArr.forEach(year => {
                    // 存储每个对象对应年份的属性名
                    let compareItemDataIndexList = []
                    // 存储每个对象对应年份的属性值
                    let compareItemDataList = []
                    for (const dataIndex in item) {
                        if (dataIndex.includes(year)) {
                            compareItemDataIndexList.push(dataIndex)
                            compareItemDataList.push(item[dataIndex])
                        }
                    }
                    // 标志为，用以对比属性值数组当中的每项是都相同
                    let itemSign = Object.values(compareItemDataList)[0]
                    // 判断数组中的每一项是否都是相同的值
                    let itemRepeat = Object.values(compareItemDataList).every(itemData => itemData == itemSign)
                    if (itemRepeat) {
                        // 此时说明这个对象中同一年份的不同bcs存在相同的值
                        compareItemDataIndexList.forEach(item => {
                            tableContent[index][item] = '-'
                        })
                    }
                })
            }

        })

        tableContent = tableContent.filter((item, index) => {
            return !arr.includes(index)
        })
    }
    return {
        yearColumns,
        tableContent
    }

}

// 当开关发生变化的时触发的回调
const hiddenSameChangeHandler = (checked: boolean) => {
    let { yearColumns, tableContent } = dealBcsCompareListDataFun(bcsCompareList, checked)
    finalColumns = yearColumns
    finalData = tableContent
    renderIndex.value++
}


// 定义一个函数用于处理BCS详情页面当中表格数据中的名字显示
const dealNameDataShow = (name: string) => {
    switch (name) {
        // 收入端部分
        case 'income':
            return '收入端'
        case 'car_output_rfq':
            return '车型产量(RFQ)'
        case 'ir_rate_rfq':
            return '搭载率(RFQ)'
        case 'car_output':
            return '车型产量'
        case 'ir_number_rfq':
            return '搭载量(RFQ)'
        case 'car_output':
            return '车型产量(调整)'
        case 'ir_rate':
            return '搭载率(调整)'
        case 'ir_number':
            return '搭载量(调整)'
        case 'hardware_price':
            return '硬件单价'
        case 'software_price':
            return '软件授权单价'
        case 'develop_one':
            return '开发费一次性补偿'
        case 'software_service':
            return '软件服务费'
        case 'hardware_income':
            return '硬件收入'
        case 'software_income':
            return '软件授权收入'

        // 第三方成本部分
        case 'three_cost':
            return '第三方成本'
        case 'hardware_buy_price':
            return '硬件采购单价'
        case 'all_buy_cost':
            return '总硬件采购成本'
        case 'supply_developer_money':
            return '供应商开发费'
        case 'three_all_cost':
            return '第三方总成本'

        // 内部平台部分 
        case 'in_platform':
            return '内部平台'
        case 'ark_sw':
            return 'ARK SW工具链分摊'
        case 'ark_develop':
            return 'ARK研发人员分摊'
        case 'software_tools':
            return '软件工具授权费'
        case 'ark_hardware_develop':
            return 'ARK硬件平台开发平摊费'
        case 'drive_platform_price':
            return '行车平台软件分摊单价'
        case 'stop_platform_price':
            return '泊车平台软件分摊单价'
        case 'base_drive_price':
            return '基础行车功能分摊单价'
        case 'other_func':
            return '其他功能分摊'
        case 'software_platform_dev':
            return '软件平台开发分摊费'

        // 客户项目研发成本部分
        case 'cus_cost':
            return '客户项目研发成本'
        case 'develop_people_cost':
            return '研发人力成本'
        case 'develop_no_people_cost':
            return '研发非人力成本'
        case 'cus_project_dev_cost':
            return '客户项目研发成本'

        // 期间成本部分
        case 'over_head':
            return '期间成本'
        case 'period_fee':
            return '期间费用'

        // 核算总览部分
        case 'over_view':
            return '核算总览'
        case 'all_develop_fee':
            return '总研发费用'
        case 'all_sales_income':
            return '总销售收入'
        case 'all_cost':
            return '总成本'
        case 'tax_profit':
            return '息税前利润'
        case 'tax_profit_percent':
            return '息税前利润百分比'
        default:
            return '未知'
    }
}


// 定义一个函数专门处理Content数据
const dealContentDataFun = (listData: any, bcsId: string) => {
    let tableHeader: {
        title: string,
        children: Array<any>
    } = {
        title: bcsId,
        children: []
    }
    listData.year_total.forEach((year: number) => {
        tableHeader.children.push({

            title: year,
            dataIndex: bcsId + year.toString(),
            key: bcsId + year.toString(),
            align: 'center'
        })
    })

    console.log('单个表头', tableHeader);

    // 遍历对象
    let tableBody: Array<any> = []
    for (const firstItem in listData) {
        // console.log(firstItem);
        if (firstItem == 'year_total') continue
        for (const secondItem in listData[firstItem]) {
            let secondObj = {
                name: dealNameDataShow(secondItem),
                basicName: secondItem,
            }
            listData[firstItem][secondItem].forEach((thirdItem: any, idx: number) => {
                if (idx < listData.year_total.length) {
                    if (typeof thirdItem == 'object') {
                        thirdItem = Object.values(thirdItem).reduce((pre, cur) => {
                            return (pre as number) * (cur as number)
                        }, 1)
                    }
                    Reflect.set(secondObj, bcsId + listData.year_total[idx].toString(), thirdItem)
                }
            })
            tableBody.push(secondObj)
        }
    }



    return {
        tableHeader,
        tableBody
    }

}


//  定义函数用于触发导出
const exportTableHandler = () => {
    console.log('需要打印的数据',selectionData,revealList);
    
    exportData(selectionData,revealList)
}
// 定义一个变量用于存储需要显示百分号的行
const showPercentList = reactive<string[]>(['ir_rate_rfq','ir_rate','tax_profit_percent'])
// 表头数据
let revealList = reactive<Array<any>>([])
// 表体数据
let selectionData = reactive<Array<any>>([])

watch([() => finalColumns, () => finalData], ([newColumns, newData]) => {
    // console.log('cecece',finalColumns,finalData);
    
    revealList = newColumns,
        selectionData = newData
}, {deep:true, immediate: true })

const exportData = (selectionData:any,revealList:any) => {

    let sheetName = 'xlsx复杂表格导出demo'
    // excel表头
    let excelHeader = buildHeader(revealList);
    // 头部行数，用来固定表头
    let headerRows = excelHeader.length;
    // 提取数据
    // console.log('传输之前的数据',selectionData,revealList);
    
    let dataList = extractData(selectionData, revealList);
    excelHeader.push(...dataList, []);
    // console.log('整体数据',excelHeader);
    
    // 计算合并
    let merges = doMerges(excelHeader)
    console.log('打印和并行',merges);
    
    // 生成sheet
    let ws = aoa_to_sheet(excelHeader, headerRows);
    // 单元格合并
    ws['!merges'] = merges;
    // 头部冻结
    ws["!freeze"] = {
        xSplit: "1",
        ySplit: "" + headerRows,
        topLeftCell: "B" + (headerRows + 1),
        activePane: "bottomRight",
        state: "frozen",
    };
    // 列宽
    ws['!cols'] = [{ wpx: 200}];
    let workbook:any = {
        SheetNames: [sheetName],
        Sheets: {}
    };
    workbook.Sheets[sheetName] = ws;
    // excel样式
    let wopts: any = {
        bookType: 'xlsx',
        bookSST: true,
        type: 'binary',
        cellStyles: true
    };
    console.log('写文件',workbook,wopts);
    // let wbout =XLSX.write(workbook, wopts);
    let wbout = write(workbook, wopts);
    // console.log('结果',wbout);
    
    // let wbout =write(workbook, wopts);
    // console.log('打印已经处理完的表格数据',workbook);
    
    let blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" });
    openDownloadXLSXDialog(blob, sheetName + '.xlsx')
}


/**
        * 构建excel表头
        * @param revealList 列表页面展示的表头
        * @returns {[]} excel表格展示的表头
        */
const buildHeader = (revealList: any) => {
    let excelHeader: Array<any> = [];
    // 构建生成excel表头需要的数据结构
    getHeader(revealList, excelHeader, 0, 0);
    // 多行表头长短不一，短的向长的看齐，不够的补上行合并占位符
    let max = Math.max(...(excelHeader.map(a => a.length)))
    excelHeader.filter(e => e.length < max).forEach(
        e => pushRowSpanPlaceHolder(e, max - e.length))
    return excelHeader;
}

/**
     * 生成头部 
     * @param headers 展示的头部
     * @param excelHeader excel头部
     * @param deep 深度
     * @param perOffset 前置偏移量
     * @returns {number}  后置偏移量
     */
const getHeader = (headers: any, excelHeader: any, deep: any, perOffset: any) => {
    let offset = 0
    let cur = excelHeader[deep]
    if (!cur) {
        cur = excelHeader[deep] = []
    }
    // 填充行合并占位符
    pushRowSpanPlaceHolder(cur, perOffset - cur.length)
    for (let i = 0; i < headers.length; i++) {
        let head = headers[i]
        cur.push(head.title)
        if (head.hasOwnProperty('children') && Array.isArray(head.children)
            && head.children.length > 0) {
            let childOffset = getHeader(head.children, excelHeader, deep + 1,
                cur.length - 1)
            // 填充列合并占位符
            pushColSpanPlaceHolder(cur, childOffset - 1)
            offset += childOffset
        } else {
            offset++
        }
    }
    return offset;

}

/**
    * 填充行合并占位符
    * */
const pushRowSpanPlaceHolder = (arr: any, count: any) => {
    for (let i = 0; i < count; i++) {
        arr.push('!$ROW_SPAN_PLACEHOLDER')
    }
}

// 填充列合并占位符
const pushColSpanPlaceHolder = (arr: any, count: any) => {
    for (let i = 0; i < count; i++) {
        arr.push('!$COL_SPAN_PLACEHOLDER')
    }
}


/**
       * 根据选中的数据和展示的列，生成结果
       * @param selectionData
       * @param revealList
       */
const extractData = (selectionData: any, revealList: any) => {
    // 列
    let headerList = flat(revealList);
    // 导出的结果集
    let excelRows: Array<any> = [];
    // 如果有child集合的话会用到
    let dataKeys = new Set(Object.keys(selectionData[0]));
    // console.log('表头1',headerList);
    // console.log('表头2',dataKeys);
    
    selectionData.some((e: any) => {
        if (e.children && e.children.length > 0) {
            let childKeys = Object.keys(e.children[0]);
            for (let i = 0; i < childKeys.length; i++) {
                dataKeys.delete(childKeys[i]);
            }
            return true;
        }
    })
    flatData(selectionData, (list: any) => {
        excelRows.push(...buildExcelRow(dataKeys, headerList, list));
        // console.log('处理后的数据',excelRows);
        
    })
    return excelRows;
}


/**
       * 展开数据，为了实现父子关系的数据进行行合并
       *   [{
       *     a:1,
       *     b:2,
       *     child: [
       *       {
       *         c:3
       *       },
       *       {
       *         c:4
       *       }
       *     ]
       *   }]
       *
       *   展开为
       *   [
       *    {
       *      a:1,
       *      b:2,
       *      c:3,
       *      rowSpan:2,
       *      child:[...]
       *    },
       *    {
       *      a:1,
       *      b:2,
       *      c:4,
       *      rowSpan:0,
       *      child:[...]
       *    }
       *   ]
       *
       *
       * @param list
       * @param eachDataCallBack
       */
const flatData = (list: any, eachDataCallBack: any) => {
    let resultList = [];
    for (let i = 0; i < list.length; i++) {
        let data = list[i];
        let rawDataList = [];
        // 每个子元素都和父元素合并成一条数据
        if (data.children && data.children.length > 0) {
            for (let j = 0; j < data.children.length; j++) {
                delete data.children[j].bsm
                let copy = Object.assign({}, data, data.children[j]);
                rawDataList.push(copy);
                copy['rowSpan'] = (j > 0 ? 0 : data.children.length);
            }
        } else {
            data['rowSpan'] = 1;
            rawDataList.push(data);
            // console.log('打印每行的数据',rawDataList);
            
        }
        resultList.push(...rawDataList);
        if (typeof eachDataCallBack === 'function') {
            eachDataCallBack(rawDataList)
        }
    }
    return resultList;
}

// 扁平头部
const flat = (revealList: any) => {
    let result: Array<any> = []
    revealList.forEach((e: any) => {
        if (e.hasOwnProperty('children')) {
            result.push(...flat(e.children))
        } else if (e.hasOwnProperty('exeFun')) {
            result.push(e)
        } else if (e.hasOwnProperty('dataIndex')) {
            result.push(e)
        }
    })
    return result;
}


/**
 *
 * 
 * */
const buildExcelRow = (mainKeys: any, headers: any, rawDataList: any) => {
    // 合计行
    let sumCols: Array<any> = [];
    // 数据行
    let rows = [];
    for (let i = 0; i < rawDataList.length; i++) {
        let cols = []
        let rawData = rawDataList[i];
        // 提取数据
        for (let j = 0; j < headers.length; j++) {
            let header = headers[j];
            // 父元素键需要行合并
            if (rawData['rowSpan'] === 0 && mainKeys.has(header.dataIndex)) {
                cols.push('!$ROW_SPAN_PLACEHOLDER')
            } else {
                let value;
                if (typeof header.exeFun === 'function') {
                    value = header.exeFun(rawData);
                } else {
                    value = rawData[header.dataIndex];
                }
                // console.log('对比',showPercentList,rawData.basicName);
                
                if (showPercentList.includes(rawData.basicName)&&header.dataIndex!='name') {
                    cols.push(`${value}%`)
                }else{
                    cols.push(value)
                }
                // 如果该列需要合计,并且是数字类型
                if (header['summable'] && typeof value === 'number') {
                    sumCols[j] = (sumCols[j] ? sumCols[j] : 0) + value;
                }
            }
        }
        rows.push(cols);
    }
    // 如果有合计行
    if (sumCols.length > 0) {
        rows.push(...sumRowHandle(sumCols));
    }
    return rows;
}

const sumRowHandle = (sumCols: any) => {
    //TODO
    return [];
}


/**
        * 合并头部单元格
        **/
const doMerges = (arr: any) => {
    // 要么横向合并 要么纵向合并
    let deep = arr.length;
    let merges = [];
    for (let y = 0; y < deep; y++) {
        // 先处理横向合并
        let row = arr[y];
        let colSpan = 0
        for (let x = 0; x < row.length; x++) {
            if (row[x] === '!$COL_SPAN_PLACEHOLDER') {
                row[x] = '';
                if (x + 1 === row.length) {
                    merges.push({ s: { r: y, c: x - colSpan - 1 }, e: { r: y, c: x } })
                }
                colSpan++
            } else if (colSpan > 0 && x > colSpan) {
                merges.push({ s: { r: y, c: x - colSpan - 1 }, e: { r: y, c: x - 1 } })
                colSpan = 0
            } else {
                colSpan = 0
            }
        }
    }
    // 再处理纵向合并
    let colLength = arr[0].length
    for (let x = 0; x < colLength; x++) {
        let rowSpan = 0
        for (let y = 0; y < deep; y++) {
            if (arr[y][x] === '!$ROW_SPAN_PLACEHOLDER') {
                arr[y][x] = '';
                if (y + 1 === deep) {
                    merges.push({ s: { r: y - rowSpan, c: x }, e: { r: y, c: x } })
                }
                rowSpan++;
            } else if (rowSpan > 0 && y > rowSpan) {
                merges.push({ s: { r: y - rowSpan - 1, c: x }, e: { r: y - 1, c: x } })
                rowSpan = 0;
            } else {
                rowSpan = 0;
            }
        }
    }
    return merges;
}


/**
        * 从github复制过来的
        */
const aoa_to_sheet = (data: any, headerRows: any) => {
    const ws:any= {};
    const range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } };
    for (let R = 0; R !== data.length; ++R) {
        for (let C = 0; C !== data[R].length; ++C) {
            if (range.s.r > R) {
                range.s.r = R;
            }
            if (range.s.c > C) {
                range.s.c = C;
            }
            if (range.e.r < R) {
                range.e.r = R;
            }
            if (range.e.c < C) {
                range.e.c = C;
            }
            console.log('打印表格数据1',data[R]);
            console.log('打印表格数据2',data[R][C]);
            
            /// 这里生成cell的时候，使用上面定义的默认样式
            const cell = {
                v: data[R][C] ,
                s: {
                    font: { name: "仿宋", sz: 12, color: { auto: 1 } },
                    alignment: {
                        /// 自动换行
                        wrapText: true,
                        // 居中
                        horizontal: "center",
                        vertical: "center",
                        // indent: 0
                    }
                }
            };
            // 头部列表加边框
            if (R < headerRows) {
                Reflect.set(cell.s, 'border', {
                    top: { style: 'thin', color: { rgb: "000000" } },
                    left: { style: 'thin', color: { rgb: "000000" } },
                    bottom: { style: 'thin', color: { rgb: "000000" } },
                    right: { style: 'thin', color: { rgb: "000000" } },
                })
                // cell.s.border = {
                //   top: { style: 'thin', color: { rgb: "000000" } },
                //   left: { style: 'thin', color: { rgb: "000000" } },
                //   bottom: { style: 'thin', color: { rgb: "000000" } },
                //   right: { style: 'thin', color: { rgb: "000000" } },
                // };
                Reflect.set(cell.s, 'fill', {
                    patternType: 'solid',
                    fgColor: { theme: 3, "tint": 0.3999755851924192, rgb: 'ffffff' },

                    // bgColor: { theme: 7, "tint": 0.3999755851924192, rgb: 'fff' }
                    
                })
                if (data[R][C]==2023) {
                    console.log('我的确时2023',data[R][C]);
                    
                    Reflect.set(cell.s, 'fill', {
                    patternType: 'solid',
                    fgColor: { theme: 3, "tint": 0.3999755851924192, rgb: 'cccccc' },
                    // bgColor: { theme: 7, "tint": 0.3999755851924192, rgb: 'fff' }
                    
                })
                }
                Reflect.set(cell.s, 'font', {
                   sz:20,
                   color:'red'
                })
                // cell.s.fill = {
                //   patternType: 'solid',
                //   fgColor: { theme: 3, "tint": 0.3999755851924192, rgb: 'DDD9C4' },
                //   bgColor: { theme: 7, "tint": 0.3999755851924192, rgb: '8064A2' }
                // }
            }
            if (data[R].includes('第三方总成本')) {
                Reflect.set(cell.s, 'fill', {
                    patternType: 'solid',
                    fgColor: { theme: 3, "tint": 0.3999755851924192, rgb: 'FFA500' },
                    // bgColor: { theme: 7, "tint": 0.3999755851924192, rgb: 'fff' }
                    
                })
            }
            // const cell_ref = XLSX.utils.encode_cell({ c: C, r: R });
            const cell_ref = utils.encode_cell({ c: C, r: R });
            if (typeof cell.v === 'number') {
                Reflect.set(cell, 't', 'n')
                // console.log('样式1',cell);
                // console.log('样式2',cell_ref);
                
                // cell.t = 'n';
            } else if (typeof cell.v === 'boolean') {
                // cell.t = 'b';
                Reflect.set(cell, 't', 'b')
            } else {
                // cell.t = 's';
                Reflect.set(cell, 't', 's')
            }
            ws[cell_ref] = cell;
            // utils.sheet_add_cell
            // console.log('需要渲染的表格',ws);
            // console.log('样式1',cell);
            //     console.log('样式2',cell_ref);
        }
    }
    if (range.s.c < 10000000) {
        // ws['!ref'] = XLSX.utils.encode_range(range);
        ws['!ref'] = utils.encode_range(range);
    }
    // console.log('测试',ws);
    
    return ws;
}


const s2ab = (s:any) => {
    let buf = new ArrayBuffer(s.length);
    let view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) {
        view[i] = s.charCodeAt(i) & 0xFF;
    }
    return buf;
}


const openDownloadXLSXDialog = (url:any, saveName:any) => {
    if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
    }
    var aLink = document.createElement('a');
    aLink.href = url;
    aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
    var event;
    if (window.MouseEvent) {
        event = new MouseEvent('click');
    } else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false,
            false, false, false, 0, null);
    }
    aLink.dispatchEvent(event);
}







onMounted(() => {
    let { yearColumns, tableContent } = dealBcsCompareListDataFun(bcsCompareList, hiddenSame.value)
    finalColumns = yearColumns
    finalData = tableContent
    revealList=yearColumns
    selectionData=tableContent
    renderIndex.value++
    // dealContentDataFun(test, '91')
})
</script>
  
<style lang="less" scoped>
:deep(.ant-table-thead>tr>th) {

    // color: #749dee !important;
    background: #fff;

}
</style>